<template>
  <!-- 内容 -->
  <div class="main">
    <!-- 帖子详情 -->
    <div class="container">
      <!-- 标题 -->
      <h6 class="mb-4">
        <img src="http://static.nowcoder.com/images/img/icons/ico-discuss.png"/>
        <span>{{ discussPost.title }}</span>
        <div class="float-right">
          <button type="button" class="btn btn-danger btn-sm" v-if="type == 1" :disabled="topDisabled">置顶</button>
          <button type="button" class="btn btn-danger btn-sm" v-if="type == 1 || type == 2" :disabled="wonderfulDisabled">加精</button>
          <button type="button" class="btn btn-danger btn-sm" v-if="type == 1 || userId == user.id" :disabled="deleteDisabled">删除</button>
        </div>
      </h6>
      <!-- 作者 -->
      <div class="media pb-3 border-bottom">
        <router-link :to="'/profile/' + user.id">
          <img :src="user.headerUrl" class="align-self-start mr-4 rounded-circle user-header" alt="用户头像" >
        </router-link>
        <div class="media-body">
          <div class="mt-0 text-warning">{{ user.username }}</div>
          <div class="text-muted mt-3">
            发布于 <b>{{ discussPost.createTime }}</b>
            <ul class="d-inline float-right">
              <li class="d-inline ml-2"><a href="#" class="text-primary" @click="like(1, id, user.id)">
                <b v-if="likeStatus == 1">已</b>赞 {{ likeCount }}</a>
              </li>
              <li class="d-inline ml-2">|</li>
              <li class="d-inline ml-2"><a href="#replyform" class="text-primary">回帖 {{ discussPost.commentCount }}</a></li>
            </ul>
          </div>
        </div>
      </div>
      <!-- 正文 -->
      <div class="mt-4 mb-3 content">
        {{ discussPost.content }}
      </div>
    </div>
    <!-- 回帖 -->
    <div class="container mt-3">
      <!-- 回帖数量 -->
      <div class="row">
        <div class="col-8">
          <h6><b class="square"></b> <i>{{ discussPost.commentCount }}</i>条回帖</h6>
        </div>
        <div class="col-4 text-right">
          <a href="#replyform" class="btn btn-primary btn-sm">&nbsp;&nbsp;回&nbsp;&nbsp;帖&nbsp;&nbsp;</a>
        </div>
      </div>
      <!-- 回帖列表 -->
      <ul class="list-unstyled mt-4">
        <!-- 回帖 -->
        <li class="media pb-3 pt-3 mb-3 border-bottom" v-for="(commentVo, index) in comments" :key="commentVo.comment.id">
          <router-link :to="'/profile/' + commentVo.user.id">
            <img :src="commentVo.user.headerUrl" class="align-self-start mr-4 rounded-circle user-header" alt="用户头像" >
          </router-link>
          <div class="media-body">
            <div class="mt-0">
              <span class="font-size-12 text-success">{{ commentVo.user.username }}</span>
              <span class="badge badge-secondary float-right floor">{{index + 1}}#</span>
            </div>
            <div class="mt-2">
              {{ commentVo.comment.content }}
            </div>
            <div class="mt-4 text-muted font-size-12">
              <span>发布于 <b>{{ commentVo.comment.createTime }}</b></span>
              <ul class="d-inline float-right">
                <li class="d-inline ml-2"><a href="#" class="text-primary" @click="like(2, commentVo.comment.id, commentVo.user.id)">
                  <b v-if="commentVo.like?.status == 1">已</b>赞 <i v-if="commentVo.like">{{ commentVo.like.count }}</i></a>
                </li>
                <li class="d-inline ml-2">|</li>
                <li class="d-inline ml-2"><a href="#" class="text-primary">回复({{ commentVo.count }})</a></li>
              </ul>
            </div>
            <!-- 回复列表 -->
            <ul class="list-unstyled mt-4 bg-gray p-3 font-size-12 text-muted">
              <!-- 回复 -->
              <li class="pb-3 pt-3 mb-3 border-bottom" v-for="replyVo in commentVo.replies" :key="replyVo.reply.id">
                <div>
                  <span>
                    <b class="text-info">
                      {{ replyVo.user.username }}
                    </b>
                    <b class="text-info" v-if="replyVo.target.id">
                      &nbsp;回复&nbsp;{{ replyVo.target.username }}
                    </b>:&nbsp;&nbsp;
                  </span>
                  <span>{{ replyVo.reply.content }}</span>
                </div>
                <div class="mt-3">
                  <span>{{ replyVo.reply.createTime }}</span>
                  <ul class="d-inline float-right">
                    <li class="d-inline ml-2"><a href="#" class="text-primary" @click="like(2, replyVo.reply.id, replyVo.user.id)">
                      <b v-if="replyVo.like?.status == 1">已</b>赞 <i v-if="replyVo.like">{{ replyVo.like.count }}</i></a>
                    </li>
                    <li class="d-inline ml-2">|</li>
                    <li class="d-inline ml-2"><a href="#huifu01" data-toggle="collapse" class="text-primary">回复</a></li>
                  </ul>
                  <div id="huifu01" class="mt-4 collapse">
                    <div>
                      <input type="text" class="input-size" :placeholder="'回复' + replyVo.user.username" v-model="replyReplyContent"/>
                    </div>
                    <div class="text-right mt-2">
                      <button type="button" class="btn btn-primary btn-sm" @click="reply(replyReplyContent, 2, commentVo.comment.id, replyVo.user.id)">
                        &nbsp;&nbsp;回&nbsp;&nbsp;复&nbsp;&nbsp;
                      </button>
                    </div>
                  </div>
                </div>
              </li>
              <!-- 回复输入框 -->
              <li class="pb-3 pt-3">
                <div>
                  <input type="text" class="input-size" placeholder="请输入你的观点" v-model="replyCommentContent"/>
                </div>
                <div class="text-right mt-2">
                  <button type="button" class="btn btn-primary btn-sm" @click="reply(replyCommentContent, 2, commentVo.comment.id)">
                    &nbsp;&nbsp;回&nbsp;&nbsp;复&nbsp;&nbsp;
                  </button>
                </div>
              </li>
            </ul>
          </div>
        </li>
      </ul>
      <!-- 分页 -->
      <div class="mt-5" v-if="discussPost.commentCount > 0">
          <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="pageSizes"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          />
      </div>
    </div>
    <!-- 回帖输入 -->
    <div class="container mt-3">
      <form class="replyform">
        <p class="mt-3">
          <a name="replyform"></a>
          <textarea placeholder="在这里畅所欲言你的看法吧!" v-model="replyPostContent" />
        </p>
        <p class="text-right">
          <button type="button" class="btn btn-primary btn-sm" @click="reply(replyPostContent, 1, id)">
            &nbsp;&nbsp;回&nbsp;&nbsp;帖&nbsp;&nbsp;
          </button>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import DiscussPost from '@/api/discussPost'
import Comment from '@/api/comment'
import Like from '@/api/like'
import { useUserStore } from '@/store/modules/user'
import router from '@/router'

const userStore = useUserStore()

const route = useRoute()

const discussPost = ref({})

const id = ref(0)

const topDisabled = ref(false)

const wonderfulDisabled = ref(false)

const deleteDisabled = ref(false)

const userId = ref(0)

const type = ref(0)

const user = ref({})

const comments = ref([])

const likeCount = ref(0)

const likeStatus = ref(0)

const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const total = ref(100)
const pageSizes = ref([5, 10, 20, 25])
const currentPage = ref(1)
const pageSize = ref(5)

const replyPostContent = ref('')

const replyCommentContent = ref('')

const replyReplyContent = ref('')

onMounted(async () => {
  id.value = route.params.id
  type.value = userStore.type
  userId.value = userStore.id
  getDiscussPostDetail()
  getLikeCount(1, id.value)
  getLikeStatus(1, id.value)
  getComments()
})

const getDiscussPostDetail = async () => {
  DiscussPost.getDiscussPostDetail(id.value)
  .then(async res => {
    discussPost.value = res.discussPost
    total.value = discussPost.value.commentCount
    user.value = res.user
    if (res.discussPost.type == 1) {
      topDisabled.value = true
    }
    if (res.discussPost.status == 1) {
      wonderfulDisabled.value = true
    }
  })
}

const getComments = async () => {
  DiscussPost.getComments(id.value, currentPage.value, pageSize.value)
  .then(async res => {
    comments.value = res
    // 动态添加like属性
    for (let i in comments.value) {
      comments.value[i].like = {
        count: 0,
        status: 0
      }
      getLikeCount(2, comments.value[i].comment.id)
      getLikeStatus(2, comments.value[i].comment.id)
      for (let j in comments.value[i].replies) {
        comments.value[i].replies[j].like = {
          count: 0,
          status: 0
        }
        getLikeCount(2, comments.value[i].replies[j].reply.id)
        getLikeStatus(2, comments.value[i].replies[j].reply.id)
      }
    }
  })
}

const handleSizeChange = async () => {
  getComments()
}

const handleCurrentChange = async () => {
  getComments()
}

const reply = async (content, entityType, entityId, targetId = 0) => {
  Comment.addComment(entityType, entityId, targetId, content)
  .then(async () => {
    // 刷新帖子回复
    if (targetId === 0) {
      getDiscussPostDetail()
      getLikeCount(1, id.value)
      getLikeStatus(1, id.value)
    }
    // 刷新评论
    getComments()
  })
}

const like = async (entityType, entityId, entityUserId) => {
  Like.like(entityType, entityId, entityUserId, id.value)
  .then(async () => {
    // 刷新状态和数量
    getLikeCount(entityType, entityId)
    getLikeStatus(entityType, entityId)
  })
}

const getLikeCount = async (entityType, entityId) => {
  Like.getLikeCount(entityType, entityId)
  .then(async res => {
    // 刷新本条
    if(entityType == 1) {
      likeCount.value = res
    } else if (entityType == 2) {
      for (let i in comments.value) {
        if (entityId == comments.value[i].comment.id) {
          comments.value[i].like.count = res
          break
        }
        for (let j in comments.value[i].replies) {
          if (entityId == comments.value[i].replies[j].reply.id) {
            comments.value[i].replies[j].like.count = res
            break
          }
        }
      }
    }
  })
}

const getLikeStatus = async (entityType, entityId) => {
  Like.getLikeStatus(entityType, entityId)
  .then(async res => {
    // 刷新本条
    if(entityType == 1) {
      likeStatus.value = res
    } else if (entityType == 2) {
      for (let i in comments.value) {
        if (entityId == comments.value[i].comment.id) {
          comments.value[i].like.status = res
          break
        }
        for (let j in comments.value[i].replies) {
          if (entityId == comments.value[i].replies[j].reply.id) {
            comments.value[i].replies[j].like.status = res
            break
          }
        }
      }
    }
  })
}

const setTop = async () => {
  if (!topDisabled.value) {
    topDisabled.value = true
    DiscussPost.setTop(id.value).then(() => {
      getDiscussPostDetail()
    }).catch(() => {
      topDisabled.value = false
    })
  }

}

const setWonderful = async () => {
  if (!wonderfulDisabled.value) {
    wonderfulDisabled.value = true
    DiscussPost.setWonderful(id.value).then(() => {
      getDiscussPostDetail()
    }).catch(() => {
      wonderfulDisabled.value = true
    })
  }
}

const setDelete = async () => {
  if (!deleteDisabled.value) {
    deleteDisabled.value = true
    DiscussPost.setDelete(id.value).then(() => {
      router.replace('/index')
    }).catch(() => {
      deleteDisabled.value = false
    })
  }
}

</script>

<style scoped>
  @import '@/style/discuss-detail.css'
</style>
